import win32api, win32gui, win32print, win32con
import pynput
import threading
import datetime
import time

print("{0} 程序启动".format(datetime.datetime.now()))

p_list = []
p_name = []


def refresh():
    global p_list, p_name
    p_list = []
    p_name = []
    p1 = win32gui.FindWindow("StartupDui", None)

    while win32gui.IsWindow(p1):
        # win32gui.SetForegroundWindow(p1)
        win_text = win32gui.GetWindowText(p1)
        p_list.append(p1)
        p_name.append(win_text)
        p1 = win32gui.FindWindowEx(None, p1, "StartupDui", None)
    if p_list == []:
        print("{0} 未找到多屏协同窗口！退出程序！".format(datetime.datetime.now()))
        exit(0)
    print("{0} 找到如下窗口：{1}".format(datetime.datetime.now(), p_name))


refresh()
on_lock = False
speed = 10  # 收缩/展开速度

width_R = win32api.GetSystemMetrics(0)
width_V = win32print.GetDeviceCaps(win32gui.GetDC(0), win32con.DESKTOPHORZRES)
zoom=round(width_V/width_R,2)   # 缩放比例，win10默认125%，按实际进行换算

def win_refresh(x, y):
    global height
    p1 = win32gui.FindWindow(None, "多屏协同")
    if win32gui.IsWindow(p1):
        (x, y) = (round(x / zoom), round(y / zoom))
        (left_n, top_n, right, bottom) = win32gui.GetWindowRect(p1)
        if x > left_n and x < right and y > top_n and y < top_n + 25:
            print("{0} 刷新窗口中".format(datetime.datetime.now()))
            refresh()


def opt_hide_show(x, y, p1, i):
    global height, p_name
    if win32gui.IsWindow(p1):
        (x, y) = (round(x / zoom), round(y / zoom))
        (left_n, top_n, right, bottom) = win32gui.GetWindowRect(p1)
        height = bottom - top_n
        if x > left_n and y < 10 and x < right:
            if bottom <= 3:
                print(
                    "{0} 展开中：窗口：{1} 坐标(x,y)= {2}".format(
                        datetime.datetime.now(), p_name[i], (x, y)
                    )
                )
                show_w(p1)
            else:
                #pass
                print(
                    "{0} 已打开：窗口：{1} 坐标(x,y)= {2}".format(
                        datetime.datetime.now(), p_name[i], (x, y)
                    )
                )
        elif bottom > 3 and top_n == 0 and (x <= left_n or x >= right):
            hide_w(p1)
            print(
                "{0} 关闭中：窗口：{1} 坐标(x,y)= {2}".format(
                    datetime.datetime.now(), p_name[i], (x, y)
                )
            )


def hide_w(p1):
    global height, speed
    win32api.keybd_event(0, 0, 0, 0)
    win32gui.SetForegroundWindow(p1)
    for i in range(1, height, speed):
        (left_n, top_n, right, bottom) = win32gui.GetWindowRect(p1)
        win32gui.SetWindowPos(p1, 0, left_n, top_n - speed, 100, 100, 1)


def show_w(p1):
    global height, speed
    win32api.keybd_event(0, 0, 0, 0)
    win32gui.SetForegroundWindow(p1)
    for i in range(1, height, speed):
        (left_n, top_n, right, bottom) = win32gui.GetWindowRect(p1)
        win32gui.SetWindowPos(p1, 0, left_n, top_n + speed, 100, 100, 1)


def on_move(x, y):
    global on_lock, p_list
    if not on_lock:
        on_lock = True
        for i in range(len(p_list)):
            threading.Thread(
                target=opt_hide_show(x, y, p_list[i], i), name='HideOrShow'
            )
        on_lock = False
    # pass


def on_click(x, y, button, pressed):
    global on_lock,height
    print(
        '{0} {1} 坐标(x,y)= {2}'.format(
            datetime.datetime.now(), '鼠标按下' if pressed else '鼠标松开', (x, y)
        )
    )
    if not pressed:
        threading.Thread(target=win_refresh(x, y), name='Refresh')
        # Stop listener
        if x < 10:
            print('{0} 退出程序'.format(datetime.datetime.now()))
            on_lock = True
            for pi in p_list:
                (left_n, top_n, right, bottom) = win32gui.GetWindowRect(pi)   
                height = bottom - top_n             
                if win32gui.IsWindow(pi) and bottom<3:
                    threading.Thread(target=show_w(pi), name='HideOrShow')
            return False


def on_scroll(x, y, dx, dy):
    # print('Scrolled {0} at {1}'.format('down' if dy < 0 else 'up',(x, y)))
    pass


with pynput.mouse.Listener(
    on_move=on_move, on_click=on_click, on_scroll=on_scroll
) as listener:
    listener.join()
